/*
 * Copyright 2012 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.chacha.socket.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.charset.Charset;

import org.chacha.cmdproxy.CommandHandler;
import org.chacha.log.LogPrn;
import org.chacha.socket.Handler;

/**
 * 
 *	@author: hejing
 *	@date: 2012-11-15-上午10:03:04
 */
public class RequestHandler implements Handler{
	private final LogPrn log = new LogPrn(getClass());
	private ChannelHelper ch;
	private SelectionKey sk;
    private ByteBuffer rbb = null;
    private Charset utf8 = Charset.forName("UTF-8");
    
	public RequestHandler(ChannelHelper ch,SelectionKey sk) throws IOException {
		this.ch=ch;
		this.sk=sk;
	}

	@Override
	public void handle(ByteBuffer bb) throws IOException {
		try{
			rbb=bb;
			rbb.flip();
			CharBuffer cb = utf8.decode(rbb);
			String reqJson=cb.toString();
			String jsonResponse=CommandHandler.handle(reqJson);
			ch.write(jsonResponse,utf8);
		}finally{
		}
	}

	@Override
	public void run() {
		try {
			handle(ch.getReadBuf());
		} catch (IOException e) {
			sk.cancel();
			try {
				ch.close();
			} catch (IOException e1) {
				log.error("RequestHandler exception "+ch.getSocketChannel().socket().getRemoteSocketAddress(),e1);
			}
			log.error("RequestHandler exception "+ch.getSocketChannel().socket().getRemoteSocketAddress(),e);
		}
	}

}
